#include <GUI/Widgets/LEDWidget.hpp>
#include <FL/Fl_PNG_Image.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Image.H>
#include <GUI/Theme.hpp>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>

// 静态成员定义（PNG）
Fl_PNG_Image* LEDWidget::s_img_on = nullptr;
Fl_PNG_Image* LEDWidget::s_img_off = nullptr;

#ifndef RESOURCE_DIR
#define RESOURCE_DIR "."
#endif

static void ensure_png_loaded()
{
    if (!LEDWidget::s_img_on)
    {
        char path_on[512];
        std::snprintf(path_on, sizeof(path_on), "%s/led_on.png", RESOURCE_DIR);
        LEDWidget::s_img_on = new Fl_PNG_Image(path_on);
        if (LEDWidget::s_img_on->fail())
        {
            std::fprintf(stderr, "[LEDWidget] 加载失败: %s\n", path_on);
            delete LEDWidget::s_img_on;
            LEDWidget::s_img_on = nullptr;
        }
    }
    if (!LEDWidget::s_img_off)
    {
        char path_off[512];
        std::snprintf(path_off, sizeof(path_off), "%s/led_off.png", RESOURCE_DIR);
        LEDWidget::s_img_off = new Fl_PNG_Image(path_off);
        if (LEDWidget::s_img_off->fail())
        {
            std::fprintf(stderr, "[LEDWidget] 加载失败: %s\n", path_off);
            delete LEDWidget::s_img_off;
            LEDWidget::s_img_off = nullptr;
        }
    }
}

LEDWidget::LEDWidget(int x, int y, int w, int h, const char* top_text, const char* bottom_text)
    : Fl_Box(x, y, w, h)
{
    box(FL_NO_BOX); // 去除自身背景
    align(FL_ALIGN_INSIDE);
    labelsize(12);
    labelfont(FL_HELVETICA);
    ensure_png_loaded();
    top_text_ = top_text ? top_text : "";
    bottom_text_ = bottom_text ? bottom_text : "";
    // 初始状态默认关
    is_on = false;
}

LEDWidget::~LEDWidget()
{
    if (cached_img_)
    {
        delete cached_img_;
        cached_img_ = nullptr;
    }
}

void LEDWidget::set_state(bool on)
{
    if (is_on == on) return;
    is_on = on;
    // 状态变化，清缓存
    if (cached_img_)
    {
        delete cached_img_;
        cached_img_ = nullptr;
    }
    cached_w_ = cached_h_ = 0;
    cached_on_ = is_on;
    redraw();
}

bool LEDWidget::get_state() const
{
    return is_on;
}

void LEDWidget::draw()
{
    // 不绘制背景，让父卡片底色透出
    // 布局：顶部文字、居中图片、底部文字
    int tx = x();
    int ty = y();
    int W = w();
    int H = h();

    const auto& th = GUI::current_theme();

    int top_h = top_h_;
    int bot_h = bottom_h_;
    if (top_text_.empty()) top_h = 0;
    if (bottom_text_.empty()) bot_h = 0;

    // 顶部文字
    if (!top_text_.empty())
    {
        fl_font(FL_HELVETICA_BOLD, 13);
        fl_color(th.text_primary);
        fl_draw(top_text_.c_str(), tx, ty, W, top_h, FL_ALIGN_CENTER | FL_ALIGN_INSIDE);
    }

    // 图片区域
    int img_y = ty + top_h;
    int img_h = std::max(0, H - top_h - bot_h);
    int img_w = W;

    Fl_PNG_Image* src = is_on ? s_img_on : s_img_off;
    if (src)
    {
        // 如果缓存尺寸或状态不同，则重建拷贝
        if (!cached_img_ || cached_w_ != img_w || cached_h_ != img_h || cached_on_ != is_on)
        {
            if (cached_img_)
            {
                delete cached_img_;
                cached_img_ = nullptr;
            }
            // 保持等比缩放，尽量塞满区域
            double sx = img_w / static_cast<double>(src->w());
            double sy = img_h / static_cast<double>(src->h());
            double s = std::min(sx, sy);
            if (s <= 0.0) s = 1.0;
            int dw = std::max(1, static_cast<int>(std::floor(src->w() * s)));
            int dh = std::max(1, static_cast<int>(std::floor(src->h() * s)));
            cached_img_ = src->copy(dw, dh);
            cached_w_ = img_w;
            cached_h_ = img_h;
            cached_on_ = is_on;
        }
        if (cached_img_)
        {
            int dx = tx + (img_w - cached_img_->w()) / 2;
            int dy = img_y + (img_h - cached_img_->h()) / 2;
            cached_img_->draw(dx, dy);
        }
    }

    // 底部文字
    if (!bottom_text_.empty())
    {
        fl_font(FL_HELVETICA_BOLD, 13);
        fl_color(th.text_secondary);
        fl_draw(bottom_text_.c_str(), tx, ty + H - bot_h, W, bot_h, FL_ALIGN_CENTER | FL_ALIGN_INSIDE);
    }
}
